package com.foreveross.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.foreveross.vo.common.MenuTree;

public class TreeUtil {
	public static List<MenuTree> getResult(List<MenuTree> src) {
		List<MenuTree> parents = new ArrayList<MenuTree>();
		for (MenuTree ent : src) {
			if (ent.getParentId().equals("0")) {
				MenuTree result = ent;
				result.setChildren(new ArrayList<MenuTree>());
				parents.add(result);
			}
		}
		List<MenuTree> last = new ArrayList<MenuTree>();
		for (MenuTree ent : src) {
			if (!ent.getParentId().equals("0")) {
				last.add(ent);
			}
		}
		buildTree(parents, last);
		return parents;
	}

	private static void buildTree(List<MenuTree> parents, List<MenuTree> others) {
		List<MenuTree> record = new ArrayList<MenuTree>();
		for (Iterator<MenuTree> it = parents.iterator(); it.hasNext();) {
			MenuTree vi = it.next();
			if (vi.getId() != null) {
				for (Iterator<MenuTree> otherIt = others.iterator(); otherIt
						.hasNext();) {
					MenuTree inVi = otherIt.next();
					if (vi.getId().equals(inVi.getParentId())) {
						if (null == vi.getChildren()) {
							vi.setChildren(new ArrayList<MenuTree>());
						}
						vi.getChildren().add(inVi);
						record.add(inVi);
						otherIt.remove();
					}
				}
			}
		}
		if (others.size() == 0) {
			return;
		} else {
			buildTree(record, others);
		}
	}
}
